import { DEFAULT_REDIS_NAMESPACE, RedisService } from '@liaoliaots/nestjs-redis';
import { HttpException, Injectable } from '@nestjs/common';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { JwtService } from '@nestjs/jwt';
import Redis from 'ioredis';
import { IRequest } from 'src/interface/common';
import { randomString } from 'src/utils';

@Injectable()
export class AuthService {
	redis:Redis
	constructor(
		private readonly jwtService: JwtService,
		private readonly redisService: RedisService,
		private readonly eventEmitter: EventEmitter2
	) {
		this.redis = this.redisService.getClient("LoginUser");
	}

	/**创建账号级别的token */
	async createAccountToken(userId:string,req: IRequest) {
		let redisKey=`LoginUser:user_${userId}`
		let loginIdentifier=randomString(32)
		let log=await this.redis.get(redisKey)
		if(log&&log!=loginIdentifier){
			//通知旧设备下线
			this.eventEmitter.emit("websocket.send.logout",{
				_id:userId,
				apiSecret:req.headers["api-secret"] == "1"||req.headers["api-secret"] == "true",
				data:""
			})
		}

		this.redis.set(redisKey,loginIdentifier)
		this.redis.expire(redisKey,86400*7)
		const payload = { date: Date.now(), _id: userId ,loginIdentifier,roleId:null};
		return {
			token: this.jwtService.sign(payload),
		};
	}
	/**创建角色级别的token */
	async createRoleToken(userId: string,roleId:string,serverId:string,loginIdentifier:string) {
		const payload = { date: Date.now(), _id: userId ,loginIdentifier,roleId,serverId};
		return {
			token: this.jwtService.sign(payload),
		};
	}

	async checkLogin(payload){
		let redisKey=`LoginUser:user_${payload._id}`
		let log=await this.redis.get(redisKey)
		if(!log){
			throw new HttpException({
				code:1,
				message:"当前登录已失效"
			},401)
		}else if(log!=payload.loginIdentifier){
			throw new HttpException({
				code:1,
				message:"您的账号已在别的设备登录，当前登录已失效"
			},401)
		}
		return true
	}
}
